package com.dynamic.datasource.factory;

import com.dynamic.datasource.property.DataSourceProperty;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.util.List;
import java.util.Objects;

/**
 * @author 王先堂
 * @Description 默认数据源工厂
 * @createTime 2022/03/24/ 11:22:00
 */
@Data
public class DefaultDataSourceFactory {

    private List<DataSourceFactory> dataSourceFactories;

    /**
     * 创建数据源
     *
     * @param dataSourceProperty 配置属性
     * @return DataSource
     */
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        if (CollectionUtils.isEmpty(dataSourceFactories)) {
            throw new IllegalStateException("DataSourceFactory must not null");
        }
        for (DataSourceFactory factory : dataSourceFactories) {
            //利用实现的工厂创建数据源
            if (Objects.nonNull(factory) && factory.isSupport(dataSourceProperty)) {
                return factory.createDataSource(dataSourceProperty);
            }
        }
        throw new IllegalStateException("not support type [" + dataSourceProperty.getType().getName() + "] DataSource");
    }
}
